# -*- coding: utf-8 -*-
import re

from PyQt5.QtWidgets import QApplication, QWidget
from base.window.base_window import BaseWidget
from utils.dialog_utils import DialogUtils
from utils.icloudp_log import IcloudpLog


class SendConfigEditApi(BaseWidget):
    def __init__(
            self,
            title: str = "Send Config Edit",
            ui_path: str = None,
            log_name: str = "log",
            parent: QWidget = None,
            app: QApplication = None,
            data: dict = None,
    ):
        self.data = data
        self.parent = parent
        self.app = app
        super().__init__(title, ui_path, log_name, parent, app)
        # self.log.warn(data)
        self.set_size(1000, 770)
        self.center()

    def custom_init(self):
        self.init_style()
        self.bind_data()
        self.init_data()

    def bind_data(self):
        self.cb_sg_dts.addItem("开启", True)
        self.cb_sg_dts.addItem("关闭", False)

        self.cb_modbus_open.addItem("开启", True)
        self.cb_modbus_open.addItem("关闭", False)
        self.cb_modbus_type.addItem("大继电器", "1")
        self.cb_modbus_type.addItem("小继电器", "0")
        self.cb_yg_yangan_dts.addItem("开启", 1)
        self.cb_yg_yangan_dts.addItem("关闭", 0)
        self.cb_yg_fbs.addItem("开启", True)
        self.cb_yg_fbs.addItem("关闭", False)

        self.cb_big_open.addItem("开启", True)
        self.cb_big_open.addItem("关闭", False)

        self.cb_dts_open.addItem("开启", True)
        self.cb_dts_open.addItem("关闭", False)

    def init_data(self):
        if self.data is None:
            return
        try:
            self.txt_sg_fault_relay.setText(str(self.data["crt"]["fault_state_relay"]))
            self.txt_sg_gaowen_relay.setText(str(self.data["crt"]["gaowen_alerm_relay"]))
            self.set_default_by_hidden_value(self.cb_sg_dts, self.data["crt"]["gaowen_alerm_dts"])
            self.txt_sg_fault_interval.setText(str(self.data["crt"]["faultStatusInterval"]))
            self.txt_sg_fiber_interval.setText(str(self.data["crt"]["fiberStatusInterval"]))
            self.txt_sg_temp_interval.setText(str(self.data["crt"]["temperatureInterval"]))
            self.txt_sg_fiber_timeout.setText(str(self.data["crt"]["temperatureTimeOut"]))
            self.txt_sg_temp_volatility.setText(str(self.data["crt"]["temperatureVolatility"]))

            self.txt_modbus_com.setText(str(self.data["crt"]["modbus_rtu"]["port"]))
            self.set_default_by_hidden_value(self.cb_modbus_open, self.data["crt"]["modbus_rtu"]["enable"])
            self.set_default_by_hidden_value(self.cb_modbus_type, self.data["crt"]["modbus_rtu"]["version"])
            self.txt_modbus_baudrate.setText(str(self.data["crt"]["modbus_rtu"]["baudrate"]))
            self.txt_modbus_interval.setText(str(self.data["crt"]["modbus_rtu"]["interval"]))
            self.txt_modbus_start.setText(str(self.data["crt"]["modbus_rtu"]["startAddress"]))
            self.txt_modbus_end.setText(str(self.data["crt"]["modbus_rtu"]["endAddress"]))

            self.txt_yg_yangan_relay.setText(str(self.data["gb"]["yangan_alerm_relay"]))
            self.set_default_by_hidden_value(self.cb_yg_yangan_dts, self.data["gb"]["yangan_alerm_dts"])
            self.txt_yg_shengguang_relays.setText(",".join(list(map(str, (self.data["gb"]["shengguang_relay"])))))
            self.txt_yg_wcs_relays.setText(",".join(list(map(str, (self.data["gb"]["wcs_relay"])))))
            self.txt_yg_fas_relays.setText(",".join(list(map(str, (self.data["gb"]["fas_relay"])))))
            self.set_default_by_hidden_value(self.cb_yg_fbs, self.data["gb"]["fbs_alerm"])

            if self.data.get("mqtt") is not None:
                self.txt_mqtt_ip.setText(str(self.data["mqtt"]["broker"]))
                self.txt_mqtt_port.setText(str(self.data["mqtt"]["port"]))
                self.txt_mqtt_user.setText(str(self.data["mqtt"]["user"]))
                self.txt_mqtt_pwd.setText(str(self.data["mqtt"]["passwd"]))
                self.txt_mqtt_id.setText(str(self.data["mqtt"]["devicedId"]))
                self.txt_mqtt_retry.setText(str(self.data["mqtt"]["alarmCheck"]))
                self.txt_mqtt_interval.setText(str(self.data["mqtt"]["tempInterva"]))

            self.txt_big_ip.setText(str(self.data["pubs"]["modbus_rtu_state"]["ip"]))
            self.txt_big_port.setText((self.data["pubs"]["modbus_rtu_state"]["port"]))
            self.set_default_by_hidden_value(self.cb_big_open, self.data["pubs"]["modbus_rtu_state"]["enable"])
            self.txt_big_interval.setText(str(self.data["pubs"]["modbus_rtu_state"]["interval"]))

            self.set_default_by_hidden_value(self.cb_dts_open, self.data["gb"]["dts_alerm"]["enable"])
            self.txt_dts_ip.setText(str(self.data["gb"]["dts_alerm"]["ip"]))
            self.txt_dts_port.setText(str(self.data["gb"]["dts_alerm"]["port"]))

        except Exception as e:
            self.log.error(f"初始数据错误: {e}")

    def init_events(self):
        self.btn_reset.clicked.connect(self.reset)
        self.btn_save.clicked.connect(self.save)

    # =======事件函数==================
    def reset(self):
        self.init_data()

    def save(self):
        try:
            self.get_data()
            self.parent.set_page_txt(self.data, 1)
            self.close()
            DialogUtils.msg("结果已输出到页面文本框，请复制粘贴或者导出到文件保存！")
            # self.parent.sys_config_dialog_win.close()
        except Exception as e:
            self.log.error(f"保存数据错误: {e}")

    # ===========自定义函数==================
    def get_data(self):
        """
        从页面获取数据
        :return:
        """
        try:
            if not self.data:
                return
            crt = self.data.get("crt")
            if not crt:
                self.log.error("crt节点不存在，请检查文件")
                DialogUtils.alert("crt节点不存在，请检查文件")
            else:
                crt["fault_state_relay"] = int(self.txt_sg_fault_relay.text())
                crt["gaowen_alerm_relay"] = int(self.txt_sg_gaowen_relay.text())
                crt["gaowen_alerm_dts"] = bool(self.get_combobox_hidden_value(self.cb_sg_dts))
                crt["faultStatusInterval"] = int(self.txt_sg_fault_interval.text())
                crt["fiberStatusInterval"] = int(self.txt_sg_fiber_interval.text())
                crt["temperatureInterval"] = int(self.txt_sg_temp_interval.text())
                crt["temperatureTimeOut"] = int(self.txt_sg_fiber_timeout.text())
                crt["temperatureVolatility"] = int(self.txt_sg_temp_volatility.text())

                modbus_rtu = crt.get("modbus_rtu")
                if not modbus_rtu:
                    self.log.error("crt.modbus_rtu节点不存在，请检查文件")
                    DialogUtils.alert("crt.modbus_rtu节点不存在，请检查文件")
                else:
                    modbus_rtu["port"] = self.txt_modbus_com.text()
                    modbus_rtu["enable"] = bool(self.get_combobox_hidden_value(self.cb_modbus_open))
                    modbus_rtu["version"] = self.get_combobox_hidden_value(self.cb_modbus_type)
                    modbus_rtu["baudrate"] = int(self.txt_modbus_baudrate.text())
                    modbus_rtu["interval"] = int(self.txt_modbus_interval.text())
                    modbus_rtu["startAddress"] = int(self.txt_modbus_start.text())
                    modbus_rtu["endAddress"] = int(self.txt_modbus_end.text())

            gb = self.data.get("gb")
            if not gb:
                self.log.error("gb节点不存在，请检查文件")
                DialogUtils.alert("gb节点不存在，请检查文件")
            else:
                gb["yangan_alerm_relay"] = int(self.txt_yg_yangan_relay.text())
                gb["yangan_alerm_dts"] = self.get_combobox_hidden_value(self.cb_yg_yangan_dts)
                if self.txt_yg_shengguang_relays.text():
                    gb["shengguang_relay"] = re.split(r'[, ，_-]', self.txt_yg_shengguang_relays.text())
                else:
                    gb["shengguang_relay"] = []
                if self.txt_yg_wcs_relays.text():
                    gb["wcs_relay"] = re.split(r'[, ，_-]', self.txt_yg_wcs_relays.text())
                else:
                    gb["wcs_relay"] = []
                if self.txt_yg_fas_relays.text():
                    gb["fas_relay"] = re.split(r'[, ，_-]', self.txt_yg_fas_relays.text())
                else:
                    gb["fas_relay"] = []
                gb["fbs_alerm"]["enable"] = bool(self.get_combobox_hidden_value(self.cb_yg_fbs))
                dts_alerm = gb.get("dts_alerm")
                if not dts_alerm:
                    self.log.error("gb.dts_alerm节点不存在，请检查文件")
                    DialogUtils.alert("gb.dts_alerm节点不存在，请检查文件")
                else:
                    dts_alerm["enable"] = bool(self.get_combobox_hidden_value(self.cb_dts_open))
                    dts_alerm["ip"] = self.txt_dts_ip.text()
                    dts_alerm["port"] = int(self.txt_dts_port.text())

            pubs = self.data.get("pubs")
            if not pubs:
                self.log.error("pubs节点不存在，请检查文件")
                DialogUtils.alert("pubs节点不存在，请检查文件")
            else:
                modbus_rtu_state = pubs.get("modbus_rtu_state")
                if not modbus_rtu_state:
                    self.log.error("pubs.modbus_rtu_state节点不存在，请检查文件")
                    DialogUtils.alert("pubs.modbus_rtu_state节点不存在，请检查文件")
                else:
                    modbus_rtu_state["ip"] = self.txt_big_ip.text()
                    modbus_rtu_state["port"] = self.txt_big_port.text()
                    modbus_rtu_state["enable"] = bool(self.get_combobox_hidden_value(self.cb_big_open))
                    modbus_rtu_state["interval"] = int(self.txt_big_interval.text())

            mqtt = self.data.get("mqtt")
            if not mqtt:
                self.log.error("mqtt节点不存在，自动添加")
                mqtt = {}
                self.data["mqtt"] = mqtt
            mqtt["ip"] = self.txt_mqtt_ip.text()
            mqtt["port"] = int(self.txt_mqtt_port.text())
            mqtt["user"] = self.txt_mqtt_user.text()
            mqtt["passwd"] = self.txt_mqtt_pwd.text()
            mqtt["equip_id"] = int(self.txt_mqtt_id.text())
            mqtt["retry"] = int(self.txt_mqtt_retry.text())
            mqtt["interval"] = int(self.txt_mqtt_interval.text())
        except Exception as e:
            self.log.error(f"获取数据错误: {e}")
